package com.freexiaoyu.freevideoplay;

import android.os.Environment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerSocketExample {
    private ServerSocket serverSocket;
    private final int PORT = 22000; // 选择一个端口号
    String outputPath = Environment.getExternalStorageDirectory() + File.separator + "Documents" + File.separator+"video.mp4";

    public void startServer() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    serverSocket = new ServerSocket(PORT);
                    while (true) {
                        // 永久循环以接受连接
                        Socket client = serverSocket.accept();
                        // 处理客户端socket
                        handleClient(client);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void handleClient(Socket client) throws IOException {
        // 处理客户端的逻辑
        // 例如，可以读取数据
        // client.getInputStream();
        if(!new File(outputPath).exists()){
            new File(outputPath).createNewFile();
        }
        InputStream inputStream = client.getInputStream();
        FileOutputStream fileOutputStream = new FileOutputStream(outputPath);

        byte[] buffer = new byte[1024];
        int bytesRead;

        // 读取视频流并写入文件
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            fileOutputStream.write(buffer, 0, bytesRead);
        }

        // 关闭流和Socket
        fileOutputStream.close();
        inputStream.close();
        serverSocket.close();
    }

    public void stopServer() {
        try {
            if (serverSocket != null) {
                serverSocket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
